import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { MemberSocialVo } from 'src/app/model/member-social-vo';
import { BtnNaviSharedService } from 'src/app/services/btn-navi-shared.service';
import { MemberService } from 'src/app/services/member.service';
import { UtilService } from 'src/app/services/util.service';

@Component({
  selector: 'app-lost-password',
  templateUrl: './lost-password.component.html',
  styles: [`
  #embed_page_form{padding:0 15px;padding-top: 20px;padding-bottom: 20px;}
  `]
})
export class LostPasswordComponent implements OnInit {
  public member: any = {
    names: '',
    email: '',
    token: ''
  };
  public errorMessage: string = '';

  constructor(
    private title: Title,
    private router: Router,
    private memberService: MemberService,
    private util: UtilService,
    private btnNaviSharedService: BtnNaviSharedService) {
    this.btnNaviSharedService.active(false); //不显示全局的导航
    this.member.token = this.util.randomAlphaNumeric(8) || '123456';
  }

  ngOnInit(): void {
    this.title.setTitle('找回帐号密码:第一步');
  }

  public querySocial(submitBtn: HTMLButtonElement): void {
    submitBtn.disabled = true;
    submitBtn.setAttribute('value', '正在提交数据...');
    //
    this.memberService.querySocial(this.member.names, this.member.email).subscribe({
      next: response => {
        let msv: MemberSocialVo = response
        if (msv.id > 0) {
          //跳转:/member/restPswd?token=&id=&hash=
          //id=member.id
          let v: any = { member: msv.member, token: this.member.token, stamp: this.util.getUnixStamp() };
          let hv: string = window.btoa(JSON.stringify(v)); //BASE64编码
          this.router.navigate(['member', 'rsetPswd'], { queryParams: { token: this.member.token, id: msv.member, hash: hv } });
        }
      },
      error: err => {
        if (err instanceof HttpErrorResponse) {
          if (err.error instanceof ErrorEvent) {
            this.errorMessage = err.error.message;
          } else {
            this.errorMessage = (err.status === 404) ? '帐号不存在或未绑定邮箱' : err.error;
          }
        } else if (err instanceof Error) {
          this.errorMessage = err.message;
        } else { this.errorMessage = err; }
        //
        submitBtn.disabled = false;
        submitBtn.setAttribute('value', '下一步');
      },
      complete: () => { console.log('[LostPassword-CTL]Completed'); }
    });
  }
}
